/*
 * @Author: wei_jt
 * @Date: 2020-11-18 19:16:07
 * @LastEditors: wei_jt
 * @LastEditTime: 2021-05-13 13:43:38
 * @Description: file content
 */
import storage from './storage';
import store from '@/store';
import Vue from 'vue';
const loadedLanguages = []; //已加载语言

function setI18nLanguage(lang) {
	Vue.config.lang = lang;
	storage.set('lang_config', lang);
	return lang;
}

export function loadLanguageAsync(lang) {
	if (!loadedLanguages.includes(lang)) {
		return import(
			/* webpackChunkName: "lang-[request]" */ `fawkes-lib/src/locale/lang/${lang}`
		).then((msgs) => {
			Vue.locale(lang, msgs.default);
			loadedLanguages.push(lang);
			return setI18nLanguage(lang);
		});
	}
	return Promise.resolve(setI18nLanguage(lang));
}

/**
 * @description: 获取本地语言设置 当未配置时，选择浏览器默认语言
 * @param {type}
 * @return:
 */
export function getLangConfig() {
	let language = storage.get('lang_config') || store.getters.language;
	if (language) return language;
	if (navigator.appName == 'Netscape') {
		language = navigator.language || navigator.userLanguage;
	} else {
		language = navigator.browserLanguage || navigator.userLanguage;
	}
	if (language.indexOf('en') > -1) {
		language = 'en';
	} else if (language.indexOf('zh') > -1) {
		language = 'zh-CN';
	} else {
		language = 'en';
	}
	return language;
}
